package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author BaiZY on 2020/9/4.
 * @version 1.0
 */
@Configuration
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId","secret"})
@EnableConfigurationProperties(ClientProperties.class)
@Slf4j
public class AuthConfiguration {
    private AuthClient authClient;
    private ClientProperties clientProperties;

    public AuthConfiguration(AuthClient authClient, ClientProperties clientProperties) {
        this.authClient = authClient;
        this.clientProperties = clientProperties;
    }

    @Bean
    @Primary
    public JwtUtils jwtUtils(StringRedisTemplate redisTemplate){
        try {
            //查询密钥
            String key = authClient.getSecretKey(clientProperties.getClientId(), clientProperties.getSecret());

            //创建JwtUitls
            JwtUtils jwtUtils = new JwtUtils(key,redisTemplate);

            //秘钥加载
            log.info("秘钥加载成功");

            return jwtUtils;
        } catch (Exception e) {
            log.error("初始化JwtUtils失败,{}", e.getMessage());
            throw e;
        }
    }
}
